package com.cinema.api.intercepter;

import com.cinema.api.annotation.DisableBaseResponse;
import com.cinema.api.model.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 数据返回统一格式
 */
@ControllerAdvice(basePackages = "com.cinema.api")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    /**
     *  实现数据集或对象转换
    */
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 是否支持advice功能 true
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //如果方法上带有DisableBaseResponse注解，不处理返回false
        return !returnType.hasMethodAnnotation(DisableBaseResponse.class);
    }

    /**
     * 对返回的数据进行处理
     * @return
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 若返回的是String,则需转换为Json格式
        if (body instanceof String) {
            return objectMapper.writeValueAsString(Result.success(body));
        }
        // 返回失败的数据 全局异常已做处理 直接返回即可
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }
}
